import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import type { UploadProps } from 'antd';
import { message, Upload } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
// const isDev = process.env.NODE_ENV === 'development';
export type UploadImageProps = {
  label?: string;
  initValue: string;
  change: (path: string) => void;
};
const UploadSingle: React.FC<UploadImageProps> = (props) => {
  const { label, change, initValue } = props;
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>(initValue !== '' ? `${initValue}` : '');
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  useEffect(() => {
    if (initValue !== '') {
      console.log(initValue);
      setImageUrl(`${initValue}`);
    } else {
      setImageUrl('');
    }
  }, [initValue]);
  const uploadButton = <div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>;
  //上传配置
  const fileType = 'image/png, image/jpeg';
  const propsUpload: UploadProps = {
    name: 'file',
    accept: fileType,
    showUploadList: false,
    maxCount: 1,
    action: `/apiupload/admin/z_file/uploadE`,
    headers: {
      Token: currentUser?.token ?? '',
    },
    beforeUpload(file) {
      setLoading(true);
      if (fileType.indexOf(file.type) !== -1) {
        return true;
      }
      message.error('你所选的文件类型不支持');
      return false;
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        setLoading(false);
      }
      if (info.file.status === 'done') {
        const res = info.file.response;
        console.log(res);
        if (res.success) {
          const filePath = res.data;
          const url = `${res.data.src}`;
          setImageUrl(url);
          change(url);
          message.success(`${info.file.name} 上传成功`);
        } else {
          message.error(`${info.file.name} 上传失败`);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };
  return (
    <div>
      <div className={styles.title}>
        <span>{label}</span>
      </div>
      <Upload {...propsUpload}>
        <div className={styles.upload}>
          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </div>
      </Upload>
    </div>
  );
};

export default UploadSingle;
